import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
  BadRequestException,
  UnauthorizedException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';
import { RedisService } from 'src/database/redis';
import { UserService } from 'src/modules/user/user.service';

@Injectable()
export class ConditionalInterceptor implements NestInterceptor {
  constructor(
    private reflector: Reflector,
    private jwtService: JwtService,
    private redisServer: RedisService,
  ) {}

  async intercept(context: ExecutionContext, next: CallHandler) {
    const skip = this.reflector.get<boolean>('skipToken', context.getHandler());
    if (skip) {
      return next.handle();
    }
    const ctx = context.switchToHttp();
    const request = ctx.getRequest<Request>();
    if (!request.headers['authorization']) {
      throw new BadRequestException('请先登录');
    }
    try {
      const token = request.headers['authorization'];
      const payload = this.jwtService.verify(token, {
        secret: 'wjnxixi',
      });

      const userCache = await this.redisServer.redis.hget(
        UserService.CreateTokenKey(payload.id),
        'token',
      );

      request['userPayload'] = {
        id: payload.id,
      };

      if (userCache === token) {
        return next.handle().pipe();
      }
      throw new UnauthorizedException('无效Token');
    } catch (error) {
      throw new UnauthorizedException('无效Token');
    }
  }
}
